<template>
    <div class="dashboard">
        <!-- 统计卡片区域 -->
        <div class="stats-cards">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-card class="stat-card" shadow="hover">
                        <div class="stat-content">
                            <div class="stat-icon users">
                                <el-icon>
                                    <User />
                                </el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ stats.totalUsers || 0 }}</div>
                                <div class="stat-label">总用户数</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card class="stat-card" shadow="hover">
                        <div class="stat-content">
                            <div class="stat-icon products">
                                <el-icon>
                                    <View />
                                </el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ stats.totalProducts || 0 }}</div>
                                <div class="stat-label">产品总数</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card class="stat-card" shadow="hover">
                        <div class="stat-content">
                            <div class="stat-icon orders">
                                <el-icon>
                                    <ShoppingCart />
                                </el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ stats.totalOrders || 0 }}</div>
                                <div class="stat-label">订单总数</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card class="stat-card" shadow="hover">
                        <div class="stat-content">
                            <div class="stat-icon revenue">
                                <el-icon>
                                    <Money />
                                </el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">¥{{ formatMoney(stats.totalRevenue || 0) }}</div>
                                <div class="stat-label">总收入</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 图表和详细信息区域 -->
        <div class="charts-section">
            <el-row :gutter="20">
                <!-- 收入趋势图 -->
                <el-col :span="16">
                    <el-card class="chart-card" shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <span>收入趋势</span>
                                <el-select v-model="chartPeriod" size="small" style="width: 120px">
                                    <el-option label="最近7天" value="7" />
                                    <el-option label="最近30天" value="30" />
                                    <el-option label="最近90天" value="90" />
                                </el-select>
                            </div>
                        </template>
                        <div class="chart-container">
                            <div ref="revenueChart" class="chart"></div>
                        </div>
                    </el-card>
                </el-col>

                <!-- 库存预警 -->
                <el-col :span="8">
                    <el-card class="alert-card" shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <span>库存预警</span>
                                <el-badge :value="inventoryAlerts.length" class="alert-badge" />
                            </div>
                        </template>
                        <div class="alert-list">
                            <div v-if="inventoryAlerts.length === 0" class="no-alerts">
                                暂无库存预警
                            </div>
                            <div v-else v-for="alert in inventoryAlerts.slice(0, 5)" :key="alert.id" class="alert-item">
                                <div class="alert-product">{{ alert.product_title }}</div>
                                <div class="alert-date">{{ alert.inventory_date }}</div>
                                <div class="alert-stock">库存: {{ alert.stock }}</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 最近订单和热门产品 -->
        <div class="details-section">
            <el-row :gutter="20">
                <!-- 最近订单 -->
                <el-col :span="12">
                    <el-card class="detail-card" shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <span>最近订单</span>
                                <el-button type="primary" size="small" text>查看全部</el-button>
                            </div>
                        </template>
                        <div class="order-list">
                            <div v-if="recentOrders.length === 0" class="no-data">
                                暂无订单数据
                            </div>
                            <div v-else v-for="order in recentOrders" :key="order.id" class="order-item">
                                <div class="order-info">
                                    <div class="order-title">{{ order.product_title }}</div>
                                    <div class="order-details">
                                        <span>订单号: {{ order.id }}</span>
                                        <span>出行日期: {{ order.travel_date }}</span>
                                    </div>
                                </div>
                                <div class="order-status">
                                    <el-tag :type="getOrderStatusType(order.status)" size="small">
                                        {{ order.status }}
                                    </el-tag>
                                    <div class="order-price">¥{{ formatMoney(order.total_price) }}</div>
                                </div>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <!-- 热门产品 -->
                <el-col :span="12">
                    <el-card class="detail-card" shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <span>热门产品</span>
                                <el-button type="primary" size="small" text>查看全部</el-button>
                            </div>
                        </template>
                        <div class="product-list">
                            <div v-if="hotProducts.length === 0" class="no-data">
                                暂无产品数据
                            </div>
                            <div v-else v-for="product in hotProducts" :key="product.id" class="product-item">
                                <div class="product-image">
                                    <el-image :src="product.cover_image || '/placeholder.jpg'" fit="cover"
                                        class="product-img" />
                                </div>
                                <div class="product-info">
                                    <div class="product-title">{{ product.title }}</div>
                                    <div class="product-stats">
                                        <span>收藏: {{ product.favorite_count || 0 }}</span>
                                        <span>订单: {{ product.order_count || 0 }}</span>
                                    </div>
                                </div>
                                <div class="product-status">
                                    <el-tag v-if="product.is_hot" type="danger" size="small">热卖</el-tag>
                                    <el-tag :type="product.status === '上架' ? 'success' : 'info'" size="small">
                                        {{ product.status }}
                                    </el-tag>
                                </div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { User, View, ShoppingCart, Money } from '@element-plus/icons-vue'
import {
    getDashboardStats,
    getRecentOrders,
    getHotProducts,
    getInventoryAlerts,
    getRevenueChart
} from '@/api/api'
import * as echarts from 'echarts'

// 响应式数据
const stats = ref({})
const recentOrders = ref([])
const hotProducts = ref([])
const inventoryAlerts = ref([])
const chartPeriod = ref('7')
const revenueChart = ref(null)
let chartInstance = null

// 格式化金额
const formatMoney = (amount) => {
    return (amount / 100).toFixed(2)
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
    const statusMap = {
        '待付款': 'warning',
        '已付款': 'success',
        '已取消': 'info',
        '已完成': 'primary'
    }
    return statusMap[status] || 'info'
}

// 初始化图表
const initChart = () => {
    if (chartInstance) {
        chartInstance.dispose()
    }

    const chartDom = revenueChart.value
    if (!chartDom) return

    chartInstance = echarts.init(chartDom)

    // 模拟数据，实际应该从API获取
    const option = {
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                return `${params[0].name}<br/>收入: ¥${formatMoney(params[0].value)}`
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: function (value) {
                    return '¥' + formatMoney(value)
                }
            }
        },
        series: [
            {
                name: '收入',
                type: 'line',
                smooth: true,
                data: [12000, 15000, 18000, 22000, 25000, 28000, 32000],
                itemStyle: {
                    color: '#409EFF'
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
                        ]
                    }
                }
            }
        ]
    }

    chartInstance.setOption(option)
}

// 加载数据
const loadData = async () => {
    try {
        // 这里应该调用实际的API，现在使用模拟数据
        stats.value = {
            totalUsers: 1250,
            totalProducts: 45,
            totalOrders: 890,
            totalRevenue: 1250000
        }

        recentOrders.value = [
            {
                id: 'ORD001',
                product_title: '张家界三日游',
                travel_date: '2024-01-15',
                status: '已付款',
                total_price: 2800
            },
            {
                id: 'ORD002',
                product_title: '三亚五日游',
                travel_date: '2024-01-20',
                status: '待付款',
                total_price: 4500
            },
            {
                id: 'ORD003',
                product_title: '丽江古城游',
                travel_date: '2024-01-25',
                status: '已完成',
                total_price: 3200
            }
        ]

        hotProducts.value = [
            {
                id: 1,
                title: '张家界三日游',
                cover_image: '/product1.jpg',
                favorite_count: 156,
                order_count: 89,
                is_hot: true,
                status: '上架'
            },
            {
                id: 2,
                title: '三亚五日游',
                cover_image: '/product2.jpg',
                favorite_count: 234,
                order_count: 156,
                is_hot: true,
                status: '上架'
            },
            {
                id: 3,
                title: '丽江古城游',
                cover_image: '/product3.jpg',
                favorite_count: 98,
                order_count: 67,
                is_hot: false,
                status: '上架'
            }
        ]

        inventoryAlerts.value = [
            {
                id: 1,
                product_title: '张家界三日游',
                inventory_date: '2024-01-15',
                stock: 5
            },
            {
                id: 2,
                product_title: '三亚五日游',
                inventory_date: '2024-01-20',
                stock: 3
            }
        ]

    } catch (error) {
        console.error('加载数据失败:', error)
    }
}

// 监听图表周期变化
watch(chartPeriod, () => {
    // 重新加载图表数据
    initChart()
})

// 组件挂载时初始化
onMounted(() => {
    loadData()
    setTimeout(() => {
        initChart()
    }, 100)

    // 监听窗口大小变化，重新调整图表
    window.addEventListener('resize', () => {
        if (chartInstance) {
            chartInstance.resize()
        }
    })
})
</script>

<style scoped>
.dashboard {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 60px);
}

/* 统计卡片样式 */
.stats-cards {
    margin-bottom: 20px;
}

.stat-card {
    border-radius: 8px;
    border: none;
}

.stat-content {
    display: flex;
    align-items: center;
    padding: 10px 0;
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    font-size: 24px;
    color: white;
}

.stat-icon.users {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.products {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.orders {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.revenue {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
    flex: 1;
}

.stat-number {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 14px;
    color: #909399;
}

/* 图表区域样式 */
.charts-section {
    margin-bottom: 20px;
}

.chart-card,
.alert-card {
    border-radius: 8px;
    border: none;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chart-container {
    height: 300px;
}

.chart {
    width: 100%;
    height: 100%;
}

/* 预警卡片样式 */
.alert-list {
    max-height: 250px;
    overflow-y: auto;
}

.alert-item {
    padding: 10px 0;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.alert-item:last-child {
    border-bottom: none;
}

.alert-product {
    font-weight: 500;
    color: #303133;
    margin-bottom: 5px;
}

.alert-date,
.alert-stock {
    font-size: 12px;
    color: #909399;
}

.no-alerts {
    text-align: center;
    color: #909399;
    padding: 20px 0;
}

/* 详细信息区域样式 */
.details-section {
    margin-bottom: 20px;
}

.detail-card {
    border-radius: 8px;
    border: none;
}

/* 订单列表样式 */
.order-list {
    max-height: 300px;
    overflow-y: auto;
}

.order-item {
    padding: 15px 0;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.order-item:last-child {
    border-bottom: none;
}

.order-info {
    flex: 1;
}

.order-title {
    font-weight: 500;
    color: #303133;
    margin-bottom: 5px;
}

.order-details {
    font-size: 12px;
    color: #909399;
}

.order-details span {
    margin-right: 15px;
}

.order-status {
    text-align: right;
}

.order-price {
    margin-top: 5px;
    font-weight: 500;
    color: #f56c6c;
}

/* 产品列表样式 */
.product-list {
    max-height: 300px;
    overflow-y: auto;
}

.product-item {
    padding: 15px 0;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    align-items: center;
}

.product-item:last-child {
    border-bottom: none;
}

.product-image {
    margin-right: 15px;
}

.product-img {
    width: 60px;
    height: 40px;
    border-radius: 4px;
}

.product-info {
    flex: 1;
}

.product-title {
    font-weight: 500;
    color: #303133;
    margin-bottom: 5px;
}

.product-stats {
    font-size: 12px;
    color: #909399;
}

.product-stats span {
    margin-right: 15px;
}

.product-status {
    text-align: right;
}

.product-status .el-tag {
    margin-left: 5px;
}

/* 通用样式 */
.no-data {
    text-align: center;
    color: #909399;
    padding: 40px 0;
}

.alert-badge {
    margin-left: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .dashboard {
        padding: 10px;
    }

    .el-col {
        margin-bottom: 20px;
    }

    .stat-content {
        flex-direction: column;
        text-align: center;
    }

    .stat-icon {
        margin-right: 0;
        margin-bottom: 10px;
    }
}
</style>